import re

class Tincl(object):
    delimiter = re.compile(r"\<\%(.*?)\%\>", re.DOTALL)
    
    def __init__(self, template):
        self.tokens = self.compile(template)
    
    @classmethod
    def compile(cls, template):
        tokens = []
        for i, part in enumerate(cls.delimiter.split(template)):
            if i % 2 == 0:
                if part:
                    tokens.append((False, part.replace("<\\%", "<%")))
            else:
                if not part.strip():
                    continue
                lines = part.replace("%\\>", "%>").replace("print(","printwrite(").splitlines()
                margin = min(len(l) - len(l.lstrip()) for l in lines if l.strip())
                realigned = "\n".join(l[margin:] for l in lines)
                code = compile(realigned, "<%r>" % (realigned[:20],), "exec")
                tokens.append((True, code))
        return tokens
    
    def render(__self, __namespace = None, **kw):
        namespace = {}
        if __namespace: namespace.update(__namespace)
        if kw: namespace.update(kw)

        def echo(*args):
            for a in args: output.append(str(a))        
        def include(*args):
            for a in args:
                file = open(a)
                source = file.read()
                t = Tincl(source)
                output.append(t())

        namespace["printwrite"] = echo
        namespace["include"] = include
        
        output = []
        for is_code, value in __self.tokens:
            if is_code:
                eval(value, namespace)
            else:
                for k, v in namespace.iteritems(): value = value.replace("{" + k + "}", str(v))
                output.append(value)
        return "".join(output)

    __call__ = render

def process(source, environ, status, response):
    t = Tincl(source)
    content = t()
    return [content, environ, status, response]

def application(environ, start_response):
    status = '200 OK'
    response = [('Content-Type', 'text/html'), ]
    file = open(environ['PATH_TRANSLATED'])
    source = file.read()
    content, environ, status, response = process(source, environ, status, response)
    start_response(status, response)
    return [content]